package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"week_exam_2_3/api/request"
	"week_exam_2_3/internal/bao"
	"week_exam_2_3/internal/model"
)

func FriendAdd(context *gin.Context) {
	var friend_add request.FriendAddRequest
	if err := context.ShouldBind(&friend_add); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	var user model.User
	context.Request.ParseForm()
	user_str := context.Request.Form.Get("user")
	json.Unmarshal([]byte(user_str), &user)
	var User model.User
	User.ID = friend_add.SeedId
	if err := bao.FundOnce(&User); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	if User.Account == "" {
		context.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": "用户不存在",
		})
		return
	}
	var AFriend model.Friend
	AFriend.UserId = user.ID
	AFriend.SeedId = User.ID
	var BFriend model.Friend
	BFriend.UserId = User.ID
	BFriend.SeedId = user.ID
	bao.Create(&AFriend)
	bao.Create(&BFriend)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "好友添加成功",
	})
	return
}
